﻿#region Usings

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

#endregion

namespace Rail.Net.Core.Model.Nonpersistent
{
    [Serializable]
    [DataContract]
    public class Product2Model
    {
        #region Constructors

        public Product2Model(int index, SearchModel searchModel, List<SequenceModel> sequences, string comfortClass)
        {
            Index = index;
            SearchModel = searchModel;
            Sequences = sequences;
            ComfortClass = comfortClass;
            PriceSegments = new List<PriceProSegment>();
            foreach (var sequenceModel in Sequences)
            {
                PriceSegments.Add(new PriceProSegment(searchModel, sequenceModel));
            }
            NumberOfFreeSeats = int.MaxValue;
        }

        #endregion

        #region Properties

        [DataMember]
        public int Index { get; set; }

        [DataMember]
        public SearchModel SearchModel { get; set; }

        [DataMember]
        public List<SequenceModel> Sequences { get; set; }

        public ConnectionModel Connection
        {
            get { return Sequences != null && Sequences.Count > 0 ? Sequences[0].Connection : null; }
        }

        [DataMember]
        public string ComfortClass { get; set; }

        [DataMember]
        public string ServiceLevelGroup { get; set; }

        [DataMember]
        public string ServiceLevel { get; set; }

        [DataMember]
        public List<PriceProSegment> PriceSegments { get; set; }

        public bool IsContengentProduct
        {
            get { return Sequences.Any(s => s is ContengentSequenceModel); }
        }

        public bool IsGlobalProduct
        {
            get { return Sequences.Any(s => s is GlobalSequenceModel); }
        }

        public bool IsDefaultProduct
        {
            get { return !IsContengentProduct && !IsGlobalProduct; }
        }

        public decimal Price
        {
            get { return PriceSegments.Sum(p => p.Price); }
            set { PriceSegments.ForEach(p => p.PricesProTraveler.ForEach(pp => pp.Price = value)); }
        }

        [DataMember]
        public int NumberOfFreeSeats
        {
            get { return PriceSegments.Min(p => p.NumberOfFreeSeats); }
            set { PriceSegments.ForEach(p => p.NumberOfFreeSeats = value); }
        }

        #endregion

        #region Methods

        public PriceProSegment GetPriceSegmentForSequence(SequenceModel sequence)
        {
            return PriceSegments.SingleOrDefault(p => p.Sequence == sequence);
        }

        #endregion
    }
}